package com.itqf.Util;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author 李鹏鹏
 * @version 1.0
 * @ClassName: DownLoad
 * @Description: TODO
 * @Date 2019/10/19 0019 上午 9:48
 * @since JDK 1.8
 * 文件下载工具
 */
public class DownLoad {
   /** @Description: 文件下载
    * @Param: verificationCode 头像名称
    * @return:
    * @Author: 李鹏鹏
    * @Date: 上午 9:51
    */
    public static ResponseEntity<byte[]> getDown(String headPortrait, HttpServletRequest request){
        //转成服务器路径
        String realPath = request.getRealPath("/upload");
        String filepath=realPath+"/"+ headPortrait;
        //创建头信息
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);//设置响应类型
        //设置弹窗方式提示用户下载
        try {
            httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(headPortrait, "utf-8"));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        File file=new File(filepath);
        ResponseEntity<byte[]> re= null;
        try {
            re = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.CREATED);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return re;

    }
}
